package com.xyy.service.impl;

import com.xyy.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件服务实现类 - 文件路径版本
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    // 图片存储根目录 - 使用绝对路径
    private static final String PICTURE_ROOT = System.getProperty("user.dir") + File.separator + "picture";
    
    // 头像存储目录
    private static final String AVATAR_DIR = "avatar";
    
    // 活动封面存储目录
    private static final String COVER_DIR = "cover";
    
    // 推文封面存储目录
    private static final String PUSH_COVER_DIR = "push_cover";

    @Override
    public String uploadAvatar(MultipartFile file) {
        try {
            log.info("开始上传头像文件");
            log.info("文件名: {}", file.getOriginalFilename());
            log.info("文件大小: {} bytes", file.getSize());
            log.info("Content-Type: {}", file.getContentType());
            
            // 检查文件类型
            if (!isValidImage(file)) {
                throw new IllegalArgumentException("不支持的文件类型，请上传图片文件");
            }

            // 检查文件大小 (限制为5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                throw new IllegalArgumentException("文件大小不能超过5MB");
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);
            String filename = generateUniqueFilename(extension);
            
            log.info("生成的文件名: {}", filename);
            log.info("文件扩展名: {}", extension);
            
            // 创建目录
            String relativePath = AVATAR_DIR + "/" + filename;
            Path fullPath = createDirectoryAndFile(relativePath);
            
            log.info("准备保存文件到: {}", fullPath);
            
            // 保存文件
            file.transferTo(fullPath.toFile());
            
            log.info("头像上传成功: {}", relativePath);
            return relativePath;

        } catch (Exception e) {
            log.error("上传头像失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public boolean isValidImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return false;
        }

        String contentType = file.getContentType();
        if (contentType == null) {
            return false;
        }

        // 检查文件扩展名
        String[] allowedExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        String lowerFilename = originalFilename.toLowerCase();
        boolean hasValidExtension = false;
        for (String ext : allowedExtensions) {
            if (lowerFilename.endsWith(ext)) {
                hasValidExtension = true;
                break;
            }
        }

        // 检查MIME类型
        boolean hasValidMimeType = contentType.startsWith("image/");

        return hasValidExtension && hasValidMimeType;
    }

    @Override
    public String uploadFile(byte[] fileBytes, String filename, String folder) {
        try {
            // 检查文件大小 (限制为10MB)
            if (fileBytes.length > 10 * 1024 * 1024) {
                throw new IllegalArgumentException("文件大小不能超过10MB");
            }

            // 生成文件名
            String extension = getFileExtension(filename);
            String newFilename = generateUniqueFilename(extension);
            
            // 创建目录
            String relativePath = folder + "/" + newFilename;
            Path fullPath = createDirectoryAndFile(relativePath);
            
            // 保存文件
            Files.write(fullPath, fileBytes);
            
            log.info("文件上传成功: {}", relativePath);
            return relativePath;

        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public String uploadCover(MultipartFile file) {
        try {
            // 检查文件类型
            if (!isValidImage(file)) {
                throw new IllegalArgumentException("不支持的文件类型，请上传图片文件");
            }

            // 检查文件大小 (限制为5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                throw new IllegalArgumentException("文件大小不能超过5MB");
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);
            String filename = generateUniqueFilename(extension);
            
            // 创建目录
            String relativePath = COVER_DIR + "/" + filename;
            Path fullPath = createDirectoryAndFile(relativePath);
            
            // 保存文件
            file.transferTo(fullPath.toFile());
            
            log.info("活动封面上传成功: {}", relativePath);
            return relativePath;

        } catch (Exception e) {
            log.error("上传活动封面失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteFile(String filePath) {
        try {
            if (filePath == null || filePath.trim().isEmpty()) {
                return false;
            }
            
            Path fullPath = Paths.get(PICTURE_ROOT, filePath);
            if (Files.exists(fullPath)) {
                Files.delete(fullPath);
                log.info("文件删除成功: {}", filePath);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("删除文件失败: {}", filePath, e);
            return false;
        }
    }

    @Override
    public String getFullPath(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return null;
        }
        return Paths.get(PICTURE_ROOT, filePath).toString();
    }

    /**
     * 创建目录并返回文件完整路径
     */
    private Path createDirectoryAndFile(String relativePath) throws IOException {
        Path fullPath = Paths.get(PICTURE_ROOT, relativePath);
        Path parentDir = fullPath.getParent();
        
        log.info("创建目录 - 相对路径: {}", relativePath);
        log.info("创建目录 - 完整路径: {}", fullPath);
        log.info("创建目录 - 父目录: {}", parentDir);
        
        if (!Files.exists(parentDir)) {
            log.info("父目录不存在，正在创建: {}", parentDir);
            Files.createDirectories(parentDir);
            log.info("父目录创建成功: {}", parentDir);
        } else {
            log.info("父目录已存在: {}", parentDir);
        }
        
        return fullPath;
    }

    /**
     * 生成唯一文件名
     */
    private String generateUniqueFilename(String extension) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        return timestamp + "_" + uuid + extension;
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return ".jpg"; // 默认扩展名
        }
        return filename.substring(filename.lastIndexOf("."));
    }
} 